<script setup>
import { ref, computed } from 'vue'
import { Edit, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 当前页码和每页显示数量
const currentPage = ref(1)
const pageSize = ref(10)

// 弹窗控制
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 弹窗模式：'add' | 'edit' | 'detail'
const dialogMode = ref('add')
const currentEditItem = ref(null)

// 表单数据
const formData = ref({
  warningLevel: '',
  level: '',
  color: '#000000',
  remark: ''
})

// 等级选项
const levelOptions = [
  { label: '0级', value: 0 },
  { label: '1级', value: 1 },
  { label: '2级', value: 2 },
  { label: '3级', value: 3 },
  { label: '4级', value: 4 }
]

// 预警级别表格数据
const warningTableData = ref([
  {
    id: 1,
    warningLevel: '正常适应',
    level: 0,
    color: '#008000',
    remark: '无预警，仅日常关注与普及教育',
    settingTime: '2025-9-20 15:00'
  },
  {
    id: 2,
    warningLevel: '轻度关注',
    level: 1,
    color: '#0000ff',
    remark: '轻度心理困扰 / 一般关注对象',
    settingTime: '2025-9-20 16:00'
  },
  {
    id: 3,
    warningLevel: '重点关注',
    level: 2,
    color: '#ffff00',
    remark: '中度心理风险 / 风险提升期',
    settingTime: '2025-9-20 17:00'
  },
  {
    id: 4,
    warningLevel: '高度风险',
    level: 3,
    color: '#ffa500',
    remark: '高危个体 / 危机前期',
    settingTime: '2025-9-20 18:00'
  },
  {
    id: 5,
    warningLevel: '危机状态',
    level: 4,
    color: '#ff0000',
    remark: '心理危机 / 紧急状态',
    settingTime: '2025-9-20 19:00'
  }
])

// 干预级别表格数据
const interventionTableData = ref([
  {
    id: 1,
    warningLevel: '常规支持',
    level: 0,
    color: '#008000',
    remark: '全员常规心理健康支持',
    settingTime: '2025-09-21 11:18'
  },
  {
    id: 2,
    warningLevel: '一般干预',
    level: 1,
    color: '#0000ff',
    remark: '班主任/辅导员日常谈心与关注',
    settingTime: '2025-09-21 11:19'
  },
  {
    id: 3,
    warningLevel: '加强干预',
    level: 2,
    color: '#ffff00',
    remark: '心理老师介入评估与随访',
    settingTime: '2025-09-21 11:20'
  },
  {
    id: 4,
    warningLevel: '重点干预',
    level: 3,
    color: '#ffa500',
    remark: '多方联合干预，建议外部评估',
    settingTime: '2025-09-21 11:21'
  },
  {
    id: 5,
    warningLevel: '危机干预',
    level: 4,
    color: '#ff0000',
    remark: '启动危机预案，紧急联系家长并转',
    settingTime: '2025-09-21 11:22'
  }
])

// 结案状态表格数据
const resultStatusTableData = ref([
  {
    id: 1,
    warningLevel: '未结案',
    level: 0,
    color: '#808080',
    remark: '干预进行中，需持续关注',
    settingTime: '2025-09-22 11:18'
  },
  {
    id: 2,
    warningLevel: '解除预警',
    level: 1,
    color: '#ff8800',
    remark: '预警解除，情况好转',
    settingTime: '2025-09-23 11:19'
  },
  {
    id: 3,
    warningLevel: '转介',
    level: 2,
    color: '#ffff00',
    remark: '已转介至专业机构',
    settingTime: '2025-09-24 11:20'
  }
])

// 预警来源表格数据
const warningSourceTableData = ref([
  {
    id: 1,
    warningLevel: '管理员添加',
    level: 1,
    color: '#0066ff',
    remark: '管理员添加（系统内置）',
    settingTime: '2025-09-25 15:15'
  },
  {
    id: 2,
    warningLevel: '个体测评',
    level: 2,
    color: '#ff0000',
    remark: '个体测评（系统内置，不可编辑或删除）',
    settingTime: '2025-09-24 15:12'
  },
  {
    id: 3,
    warningLevel: '团体测评',
    level: 3,
    color: '#ff8800',
    remark: '团体测评（系统内置，不可编辑或删除）',
    settingTime: '2025-09-24 15:13'
  },
  {
    id: 4,
    warningLevel: '用户端自测',
    level: 4,
    color: '#00ff00',
    remark: '用户端自测（系统内置）',
    settingTime: '2025-09-26 15:16'
  }
])

// 当前显示的表格数据（根据选中的标签页）
const currentTableData = computed(() => {
  if (activeTab.value === 'warning-list') {
    return warningTableData.value
  } else if (activeTab.value === 'intervention-level') {
    return interventionTableData.value
  } else if (activeTab.value === 'result-status') {
    return resultStatusTableData.value
  } else if (activeTab.value === 'warning-source') {
    return warningSourceTableData.value
  }
  return []
})

// 当前页表格数据
const currentPageTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return currentTableData.value.slice(start, end)
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 重置表单
const resetForm = () => {
  formData.value = {
    warningLevel: '',
    level: '',
    color: '#000000',
    remark: ''
  }
}

// 获取当前操作的数据源
const getCurrentDataSource = () => {
  if (activeTab.value === 'warning-list') {
    return warningTableData
  } else if (activeTab.value === 'intervention-level') {
    return interventionTableData
  } else if (activeTab.value === 'result-status') {
    return resultStatusTableData
  } else if (activeTab.value === 'warning-source') {
    return warningSourceTableData
  }
  return warningTableData // 默认返回预警级别
}



// 确认添加或编辑
const confirmAdd = () => {
  // 表单验证
  if (!formData.value.warningLevel) {
    ElMessage.error(`请输入${getCurrentColumnLabel()}`)
    return
  }
  // 预警级别和干预级别标签页需要验证等级
  if ((activeTab.value === 'warning-list' || activeTab.value === 'intervention-level')) {
    if (!formData.value.level) {
      ElMessage.error('请输入等级')
      return
    }
    // 验证等级是否为数字
    const levelNum = parseInt(formData.value.level)
    if (isNaN(levelNum)) {
      ElMessage.error('等级必须是数字')
      return
    }
  }

  const dataSource = getCurrentDataSource()

  if (dialogMode.value === 'add') {
    // 添加模式
    const newId = Math.max(...dataSource.value.map(item => item.id)) + 1

    const newItem = {
      id: newId,
      warningLevel: formData.value.warningLevel,
      level: parseInt(formData.value.level) || formData.value.level,
      color: formData.value.color,
      remark: formData.value.remark,
      settingTime: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }).replace(/\//g, '-')
    }

    dataSource.value.push(newItem)
    ElMessage.success('添加成功')
  } else if (dialogMode.value === 'edit') {
    // 编辑模式
    const index = dataSource.value.findIndex(item => item.id === currentEditItem.value.id)
    if (index !== -1) {
      dataSource.value[index] = {
        ...currentEditItem.value,
        warningLevel: formData.value.warningLevel,
        level: parseInt(formData.value.level) || formData.value.level,
        color: formData.value.color,
        remark: formData.value.remark,
        settingTime: currentEditItem.value.settingTime // 保持原设置时间
      }
      ElMessage.success('编辑成功')
    }
  }

  // 关闭弹窗
  dialogVisible.value = false
}

// 取消添加
const cancelAdd = () => {
  dialogVisible.value = false
  resetForm()
}



// 预警级别初始数据
const initialWarningData = [
  {
    id: 1,
    warningLevel: '正常适应',
    level: 0,
    color: '#008000',
    remark: '无预警，仅日常关注与普及教育',
    settingTime: '2025-10-14 15:00'
  },
  {
    id: 2,
    warningLevel: '轻度关注',
    level: 1,
    color: '#0000ff',
    remark: '轻度心理困扰 / 一般关注对象',
    settingTime: '2025-10-14 16:00'
  },
  {
    id: 3,
    warningLevel: '重点关注',
    level: 2,
    color: '#ffff00',
    remark: '中度心理风险 / 风险提升期',
    settingTime: '2025-10-14 17:00'
  },
  {
    id: 4,
    warningLevel: '高度风险',
    level: 3,
    color: '#ffa500',
    remark: '高危个体 / 危机前期',
    settingTime: '2025-10-14 18:00'
  },
  {
    id: 5,
    warningLevel: '危机状态',
    level: 4,
    color: '#ff0000',
    remark: '心理危机 / 紧急状态',
    settingTime: '2025-10-14 19:00'
  }
]

// 干预级别初始数据
const initialInterventionData = [
  {
    id: 1,
    warningLevel: '常规支持',
    level: 0,
    color: '#008000',
    remark: '全员常规心理健康支持',
    settingTime: '2023-03-06 11:18'
  },
  {
    id: 2,
    warningLevel: '一般干预',
    level: 1,
    color: '#0000ff',
    remark: '班主任/辅导员日常谈心与关注',
    settingTime: '2023-03-06 11:19'
  },
  {
    id: 3,
    warningLevel: '加强干预',
    level: 2,
    color: '#ffff00',
    remark: '心理老师介入评估与随访',
    settingTime: '2023-03-06 11:20'
  },
  {
    id: 4,
    warningLevel: '重点干预',
    level: 3,
    color: '#ffa500',
    remark: '多方联合干预，建议外部评估',
    settingTime: '2023-03-06 11:21'
  },
  {
    id: 5,
    warningLevel: '危机干预',
    level: 4,
    color: '#ff0000',
    remark: '启动危机预案，紧急联系家长并转',
    settingTime: '2023-03-06 11:22'
  }
]

// 结案状态初始数据
const initialResultStatusData = [
  {
    id: 1,
    warningLevel: '未结案',
    level: 0,
    color: '#808080',
    remark: '干预进行中，需持续关注',
    settingTime: '2023-03-06 11:18'
  },
  {
    id: 2,
    warningLevel: '解除预警',
    level: 1,
    color: '#ff8800',
    remark: '预警解除，情况好转',
    settingTime: '2023-03-06 11:19'
  },
  {
    id: 3,
    warningLevel: '转介',
    level: 2,
    color: '#ffff00',
    remark: '已转介至专业机构',
    settingTime: '2023-03-06 11:20'
  }
]

// 预警来源初始数据
const initialWarningSourceData = [
  {
    id: 1,
    warningLevel: '管理员添加',
    level: 1,
    color: '#0066ff',
    remark: '管理员添加（系统内置）',
    settingTime: '2022-11-17 15:12'
  },
  {
    id: 2,
    warningLevel: '个体测评',
    level: 2,
    color: '#ff0000',
    remark: '个体测评（系统内置，不可编辑或删除）',
    settingTime: '2022-11-17 16:12'
  },
  {
    id: 3,
    warningLevel: '团体测评',
    level: 3,
    color: '#ff8800',
    remark: '团体测评（系统内置，不可编辑或删除）',
    settingTime: '2022-11-17 17:12'
  },
  {
    id: 4,
    warningLevel: '用户端自测',
    level: 4,
    color: '#00ff00',
    remark: '用户端自测（系统内置）',
    settingTime: '2022-11-17 18:12'
  }
]



// 编辑设置
const editSetting = (row) => {
  dialogMode.value = 'edit'
  currentEditItem.value = { ...row }

  // 预填充表单数据
  formData.value = {
    warningLevel: row.warningLevel,
    level: row.level,
    color: row.color,
    remark: row.remark
  }

  dialogVisible.value = true
}

// 删除设置
const deleteSetting = (row) => {
  ElMessageBox.confirm(
    `确定要删除预警级别"${row.warningLevel}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const dataSource = getCurrentDataSource()
    // 找到要删除的项目索引
    const index = dataSource.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      // 从数组中删除
      dataSource.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除')
  })
}

// 查看详情
const viewDetail = (row) => {
  currentEditItem.value = { ...row }
  detailDialogVisible.value = true
}

// 当前激活的标签页
const activeTab = ref('warning-list')

// 获取当前标签页的列标题
const getCurrentColumnLabel = () => {
  if (activeTab.value === 'intervention-level') {
    return '干预级别'
  } else if (activeTab.value === 'result-status') {
    return '结案状态'
  } else if (activeTab.value === 'warning-source') {
    return '来源'
  }
  return '预警级别' // 默认为预警级别
}

// 标签页切换处理
const handleTabClick = (tab) => {
  console.log('切换到标签页:', tab.props.name)
}
</script>

<template>
<div class="warning-setting-container">
    <!-- 标签页区域 -->
    <div class="top1">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="预警级别" name="warning-list"></el-tab-pane>
            <el-tab-pane label="干预级别" name="intervention-level"></el-tab-pane>
            <el-tab-pane label="结案状态" name="result-status"></el-tab-pane>
            <el-tab-pane label="预警来源" name="warning-source"></el-tab-pane>
        </el-tabs>
    </div>

    <!-- 表格区域 -->
    <div class="table-box">
        <el-table
            :data="currentPageTableData"
            style="width: 100%"
            height="400"
            :header-cell-style="{ 'background-color': '#f5f7fa', 'text-align': 'left' }"
            :cell-style="{ 'text-align': 'left' }"
        >
            <el-table-column prop="warningLevel" :label="getCurrentColumnLabel()" min-width="120" />
            <el-table-column prop="level" label="等级" min-width="80" v-if="activeTab === 'warning-list' || activeTab === 'intervention-level'" />
            <el-table-column label="标记色" min-width="100" align="left" v-if="activeTab !== 'result-status' && activeTab !== 'warning-source'">
                <template #default="scope">
                    <div class="color-cell-container">
                        <div
                            class="color-block"
                            :style="{ backgroundColor: scope.row.color }"
                        ></div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="200" />
            <el-table-column prop="settingTime" label="操作时间" min-width="180" />
            <el-table-column fixed="right" label="操作" width="250">
                <template #default="scope">
                    <span style="color: #409EFF; cursor: pointer; margin-right: 15px;" @click="viewDetail(scope.row)">
                        查看
                    </span>
                    <span style="color: #409EFF; cursor: pointer; margin-right: 15px;" @click="editSetting(scope.row)">
                        编辑
                    </span>
                    <span style="color: #F56C6C; cursor: pointer;" @click="deleteSetting(scope.row)">
                        删除
                    </span>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogMode === 'add' ? '添加' : '编辑'"
        width="500px"
        :close-on-click-modal="false"
        :before-close="cancelAdd"
    >
        <el-form :model="formData" label-width="80px">
            <el-form-item :label="getCurrentColumnLabel()" required>
                <el-input
                    v-model="formData.warningLevel"
                    :placeholder="`请输入${getCurrentColumnLabel()}`"
                />
            </el-form-item>

            <el-form-item label="等级" required v-if="activeTab === 'warning-list' || activeTab === 'intervention-level'">
                <el-input
                    v-model="formData.level"
                    placeholder="请输入等级（数字）"
                    oninput="value=value.replace(/[^0-9]/g,'')"
                />
            </el-form-item>

            <el-form-item label="标记色" v-if="activeTab !== 'result-status' && activeTab !== 'warning-source'">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <el-color-picker v-model="formData.color" />
                    <div class="color-preview" :style="{ backgroundColor: formData.color }"></div>
                </div>
            </el-form-item>

            <el-form-item label="备注">
                <el-input
                    v-model="formData.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    :rows="3"
                />
            </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelAdd">取消</el-button>
            <el-button type="primary" @click="confirmAdd">
              {{ dialogMode === 'add' ? '确定' : '保存' }}
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 详情弹窗 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="详情"
        width="500px"
        :close-on-click-modal="false"
      >
        <div v-if="currentEditItem" class="detail-content">
          <div class="detail-item">
            <label>{{ getCurrentColumnLabel() }}：</label>
            <span>{{ currentEditItem.warningLevel }}</span>
          </div>
          <div class="detail-item" v-if="activeTab === 'warning-list' || activeTab === 'intervention-level'">
            <label>等级：</label>
            <span>{{ currentEditItem.level }}</span>
          </div>
          <div class="detail-item" v-if="activeTab !== 'result-status' && activeTab !== 'warning-source'">
            <label>标记色：</label>
            <div class="color-display" :style="{ backgroundColor: currentEditItem.color }"></div>
          </div>
          <div class="detail-item">
            <label>备注：</label>
            <span>{{ currentEditItem.remark || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>操作时间：</label>
            <span>{{ currentEditItem.settingTime }}</span>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
</div>
</template>

<style scoped>
div {
    overflow: hidden;
}
.top1 {
    padding: 2px 0px 0px 10px;
    min-height: 40px;
}

.button-area {
    padding: 2px 0px 0px 10px;
    text-align: right;
}
.table-box {
    padding-left: 10px;
    margin-top: 20px;
}

.detail-content {
  padding: 20px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.detail-item label {
  width: 80px;
  font-weight: bold;
  color: #606266;
}

.detail-item span {
  color: #303133;
}

.color-display {
  width: 40px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.color-preview {
  width: 40px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.color-cell-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
}

.color-block {
    width: 40px;
    height: 20px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
}

.warning-setting-container {
    padding: 20px;
}
</style>
